const jwt = require('jsonwebtoken')
const {getOauthToken, getAliPayUserInfo} = require("../config/alipay");
const {getWxOauthToken} = require("../config/weixin");
const {
    createOrUpdateUserServe,
    findWxUserByIdServe,
    createWxUserServe,
    updateWxUserTokenServe
} = require("../serve/appletUser.serve")
const {getCollectByUserIdServe} = require("../serve/appletBikeCollect.serve")
const {getCommentByUserIdServe} = require("../serve/comment.serve")
const {JWT_SECRET, generateRandomString} = require('../utils')
const redis = require('../utils/redis')
const {WxAppletUser} = require("../db/seq");

class AppletUserController {
    async login(ctx) {
        const {authCode} = ctx.request.body;
        try {
            if (!authCode) {
                throw({message: 'authCode为空'})
            }
            const res = await getOauthToken(authCode)
            if (res && res.accessToken) {
                const userInfo = await getAliPayUserInfo(res.accessToken);
                console.log(userInfo)
                if (userInfo.code === '40002') {
                    throw ({message: userInfo.subMsg})
                }
                const {nickName, avatar, openId} = userInfo
                const appletUsers = await createOrUpdateUserServe(nickName, avatar, openId)
                if (appletUsers.length > 0) {
                    const userId = appletUsers[0].dataValues.id
                    //1，现在redis查当前用户是否为登陆状态
                    const isLogin = await redis.get(`applet${userId}`);
                    let token = ''
                    if (isLogin && JSON.parse(isLogin).token) { //如果当前用户已经登录，说明在redis已经存储当前用户的token信息，就不用重新生成token了
                        token = JSON.parse(isLogin).token
                    } else {
                        token = jwt.sign({openId, nickName, id: userId, avatar}, JWT_SECRET, {expiresIn: '1d'})
                        let setRedisStatus = await redis.set(`applet${userId}`, JSON.stringify({token}))
                        redis.expire(`applet${userId}`, 60 * 60 * 12)
                        if (setRedisStatus !== 'OK') {
                            console.log('存储redis失败')
                            throw({message: '服务器出现问题'})
                        }
                    }
                    ctx.body = {
                        status: 0,
                        msg: '用户登陆成功',
                        data: {
                            token,
                            userInfo: {
                                nickName,
                                avatar,
                                userId,
                                openId
                            }
                        }
                    }
                } else {
                    throw ({message: '服务器出现问题'})
                }
            } else {
                throw ({message: '服务器出现问题'})
            }
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message
            }
        }
    }

    async wxLogin(ctx) {
        const {code} = ctx.request.body;
        try {
            if (!code) {
                throw({message: 'code为空'})
            }
            const res = await getWxOauthToken(code)
            if (Number(res.status) === 200) {
                if (res.data && res.data.openid) {
                    const {openid, session_key} = res.data
                    const isHasWxUser = await findWxUserByIdServe({openid})
                    let token;
                    let userId;
                    let nicknameRes;
                    if (isHasWxUser) {
                        const {nickName, id} = isHasWxUser.dataValues
                        token = jwt.sign({nickName, id}, JWT_SECRET)
                        userId= id
                        nicknameRes = nickName
                    } else {
                        let nickName = generateRandomString(10)
                        const wxAppletUsers = await createWxUserServe({
                            openId: openid,
                            nickName,
                            sessionKey: session_key
                        })
                        //为什么要写这一步，是因为先生成一个用户数据才能有用户id，需要根据用户id生成token
                        if (wxAppletUsers) {
                            const {id, nickName} = wxAppletUsers.dataValues
                            nicknameRes = nickName
                            token = jwt.sign({nickName, id}, JWT_SECRET)
                            userId= id
                            const isUpdate = await updateWxUserTokenServe(token, id)
                            if (!isUpdate) {
                                throw ({message: '登录失败'})
                            }
                        }
                    }
                    ctx.body = {
                        status: 0,
                        msg: '登录成功',
                        data: {
                            token,
                            userInfo: {
                                nickName: nicknameRes,
                                userId
                            }
                        }
                    }
                } else {
                    throw ({message: res.data.errmsg })
                }
            }
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message
            }
        }
    }

    async logout(ctx) {
        console.log(ctx.request.url.includes('wx'));
        // 1.获取到当前用户id
        console.log(ctx.state.appletUser)
        let userId = ctx.state.appletUser.id;
        try {
            if (!ctx.request.url.includes('wx')) {
                // 2.根据用户id查找redis是否有以此id为key值得对象
                let res = await redis.get(`applet${userId}`)
                // 3.如果找到该id存储得对象，并且有token
                if (res && JSON.parse(res).token) {
                    //4.删除该id对象
                    await redis.del(`applet${userId}`)
                    ctx.body = {
                        status: 0,
                        msg: '退出登录成功',
                        data: null
                    }
                } else {
                    throw ({message: '查找不到该用户'})
                }
            } else {
                let res = await updateWxUserTokenServe('', userId)
                if (res) {
                    ctx.body = {
                        status: 0,
                        msg: '退出登录成功',
                        data: null
                    }
                }
            }
        } catch (e) {
            console.log(e);
            ctx.body = {
                status: 1,
                msg: '退出登录失败',
                data: null
            }
        }
    }

    async getStarNum(ctx) {
        try {
            const {id: userId} = ctx.state.appletUser;
            const collectBike = await getCollectByUserIdServe({userId, isAll: true})
            const commentBike = await getCommentByUserIdServe({createdUserId: userId, isAll: true})
            ctx.body = {
                status: 0,
                msg: '获取成功',
                data: {
                    collectNum: collectBike.length,
                    commentNum: commentBike.length
                }
            }
        } catch (e) {
            ctx.body = {
                status: 1,
                msg: e.message,
                data: null
            }
        }
    }

    async getWxUserList(ctx) {
        try {
            const res = await WxAppletUser.findAll()
            ctx.body = {
                data: res
            }
        }catch (e) {
            return ctx.body = {
                status: 1,
                msg: e.message,
                data: null
            }
        }
    }
}

module.exports = new AppletUserController()
